package com.ssm.reactive.service;

import com.ssm.reactive.domain.Employee;
import com.ssm.reactive.repository.IEmployeeRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.transaction.reactive.TransactionalOperator;
import org.springframework.util.Assert;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
@RequiredArgsConstructor
public class EmployeeService {
    // final EmployeeRepository employeeRepository;
    final IEmployeeRepository employeeRepository;
    final TransactionalOperator transactionalOperator;

    public Mono<Employee> save(Employee employee) {
        return employeeRepository.save(employee);
    }

    public Flux<Employee> saveAll(List<Employee> employees) {
        return this.transactionalOperator.transactional(Flux.fromIterable(employees)
                .flatMap(this.employeeRepository::save)
                .doOnNext(e -> Assert.isTrue(isValid(e.getUsername()), "The name must have a capital first letter!")));
    }

    boolean isValid(String name) {
        return Character.isUpperCase(name.charAt(0));
    }

    public Mono<Employee> findById(Long id) {
        return employeeRepository.findById(id);
    }

    public Flux<Employee> findAll() {
        return employeeRepository.findAll();
    }

    public Mono<Employee> update(Employee employee) {
        return employeeRepository.findById(employee.getId());
    }

    public Mono<Void> deleteById(Long id) {
        return employeeRepository.deleteById(id);
    }
}
